package com.selfdiscipline.data.local

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.selfdiscipline.data.model.Task
import com.selfdiscipline.data.model.TaskWithSubtasks
import kotlinx.coroutines.flow.Flow

/**
 * Data Access Object for Task entity
 */
@Dao
interface TaskDao {
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertTask(task: Task): Long
    
    @Update
    suspend fun updateTask(task: Task)
    
    @Delete
    suspend fun deleteTask(task: Task)
    
    @Query("SELECT * FROM tasks WHERE id = :taskId")
    fun getTaskById(taskId: String): Flow<Task?>
    
    @Query("SELECT * FROM tasks WHERE parent_task_id IS NULL ORDER BY created_at DESC")
    fun getAllParentTasks(): Flow<List<Task>>
    
    @Query("SELECT * FROM tasks WHERE parent_task_id = :parentTaskId ORDER BY created_at ASC")
    fun getSubtasksForParent(parentTaskId: String): Flow<List<Task>>
    
    @Transaction
    @Query("SELECT * FROM tasks WHERE id = :taskId")
    fun getTaskWithSubtasks(taskId: String): Flow<TaskWithSubtasks?>
    
    @Query("SELECT * FROM tasks WHERE completed = 0 AND parent_task_id IS NULL ORDER BY deadline ASC, priority ASC")
    fun getPendingTasks(): Flow<List<Task>>
    
    @Query("SELECT * FROM tasks WHERE completed = 1 ORDER BY completed_at DESC")
    fun getCompletedTasks(): Flow<List<Task>>
    
    @Query("UPDATE tasks SET completed = 1, completed_at = :completionTime WHERE id = :taskId")
    suspend fun markTaskAsCompleted(taskId: String, completionTime: Long)
    
    @Query("DELETE FROM tasks WHERE id = :taskId OR parent_task_id = :taskId")
    suspend fun deleteTaskAndSubtasks(taskId: String)
    
    @Query("SELECT COUNT(*) FROM tasks WHERE completed = 1 AND completed_at BETWEEN :startTime AND :endTime")
    fun getCompletedTasksCountInPeriod(startTime: Long, endTime: Long): Flow<Int>
} 